package com.feihong.txgw.shopcar.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.adapter.base.animation.ScaleInAnimation;
import com.bumptech.glide.Glide;
import com.feihong.txgw.R;
import com.feihong.txgw.adapter.Holder.BaseViewHolder;
import com.feihong.txgw.anim.TxListAnimation;
import com.feihong.txgw.model.greendao.ShopCarGoodsModel;
import com.feihong.txgw.shopcar.listener.GoodsCountChangeListener;
import com.feihong.txgw.shopcar.listener.GoodsSelectStatusListener;
import com.feihong.txgw.shopcar.listener.ShopCarDelFailureGoodsListener;
import com.feihong.txgw.shopcar.viewholder.ShopCarFailureDevideViewHolder;
import com.feihong.txgw.shopcar.viewholder.ShopCarFailureViewHolder;
import com.feihong.txgw.ui.activity.base.BaseActivity;
import com.feihong.txgw.ui.activity.product.ProductInfoActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.feihong.txgw.ui.fragment.home.DiscoverFragment.INTENT_PRODUCTID;

/**
 * @name txgw_app
 * @class name：com.feihong.txgw.shopcar.adapter
 * @class describe: 购物车适配器
 * @author wangziheng
 * @time 2017/6/29 13:23
 * @change
 * @chang time
 * @class describe
 */
public class ShopCarAdapter extends RecyclerView.Adapter<BaseViewHolder> {

    private BaseActivity mContext;
    private List<ShopCarGoodsModel> mGoodsList;
    private GoodsSelectStatusListener mGoodsSelectStatusListener;

    private ArrayList<ShopCarGoodsModel> mFailureGoodsList;
    private ArrayList<ShopCarGoodsModel> mNormalGoodsList;
    private final int FAILURE_GOODS = 0;
    private final int NORMAL_GOODS = 1;
    private final int FAILURE_GOODS_DEVIDE = 2;

    private TxListAnimation mTxListAnimation;
    public ShopCarAdapter(Context context) {
        mContext = (BaseActivity) context;
        mGoodsList = new ArrayList<>();
        mFailureGoodsList = new ArrayList<>();
        mNormalGoodsList = new ArrayList<>();
        mTxListAnimation = new TxListAnimation();
        mTxListAnimation.addAnimation(new ScaleInAnimation(0.8f));
        mTxListAnimation.setFirstOnly(true);
    }

    @Override
    public void onViewAttachedToWindow(@NonNull BaseViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        mTxListAnimation.setHolder(holder);
    }

    /**
     * 清空数据
     */
    public void setClearData() {
        mGoodsList.clear();
        mFailureGoodsList.clear();
        mNormalGoodsList.clear();
        notifyDataSetChanged();
    }

    /**
     * 添加数据集合
     *
     * @param goodsList
     */
    public void setGoodsList(List<ShopCarGoodsModel> goodsList) {
        mFailureGoodsList.clear();
        mNormalGoodsList.clear();
        mGoodsList = goodsList;
        if(mGoodsList != null){
            for (ShopCarGoodsModel dbGoodsCartModel : mGoodsList) {
                if (dbGoodsCartModel.getGoodsStatus() == 0) {
                    mFailureGoodsList.add(dbGoodsCartModel);
                } else {
                    mNormalGoodsList.add(dbGoodsCartModel);
                }
            }
        }
        notifyDataSetChanged();
    }

    /**
     * 添加单条数据
     * //     * @param goods
     */
//    public void setGoods(DbGoodsCartModel goods){
//        mGoodsList.add(goods);
//        notifyDataSetChanged();
//    }
    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == NORMAL_GOODS) {
            return new ShopCarViewHolder(LayoutInflater.from(mContext).inflate(R.layout.shopcar_item_layout, parent, false));
        } else if (viewType == FAILURE_GOODS_DEVIDE) {
            return new ShopCarFailureDevideViewHolder(mContext, LayoutInflater.from(mContext).inflate(R.layout.shopcar_failure_devider_layout, parent, false));
        } else if (viewType == FAILURE_GOODS) {
            return new ShopCarFailureViewHolder(mContext, LayoutInflater.from(mContext).inflate(R.layout.shopcar_item_layout, parent, false));
        }
        return null;
    }

    @Override
    public void onBindViewHolder(final BaseViewHolder holder, final int position) {
        if (getItemViewType(position) == NORMAL_GOODS) {
            final ShopCarViewHolder mHolder = (ShopCarViewHolder) holder;
            final ShopCarGoodsModel goodsEntity = mNormalGoodsList.get(position);
            mHolder.mItemGoodsName.setText(goodsEntity.getGoodsName());
            mHolder.mItemGoodsCount.setText(goodsEntity.getGoodsNum() + "");
            StringBuffer stringBuffer = new StringBuffer();
            try {
                if (goodsEntity.getGoodsSpec() != null) {
                    JSONArray jsonArray = new JSONArray(goodsEntity.getGoodsSpec());
                    if (jsonArray != null) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.optJSONObject(i);
                            stringBuffer.append(jsonObject.optString("name") + ":" + jsonObject.optString("value") + "   ");
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            mHolder.mItemGoodsDescribe.setText(stringBuffer.toString());

//        BigDecimal a1 = new BigDecimal());
//        BigDecimal a2 = new BigDecimal(Double.toString(goodsEntity.getGoogdsnum()));
//        BigDecimal result = a1.multiply(a2);
//        BigDecimal one = new BigDecimal("1");
//
//        DecimalFormat df = new DecimalFormat("######0.00");
//        String strPrice = df.format(result.divide(one, 2, BigDecimal.ROUND_HALF_UP).doubleValue());
//            String[] strings = String.valueOf(goodsEntity.getGoodsprice()).split("\\.");

//            mHolder.mItemGoodsPrice.setText(strings[0] + ".");
            mHolder.mItemGoodsPrice.setText("¥"+goodsEntity.getGoodsPrice());
//            mHolder.mItemGoodsPriceRemainder.setText(strings[1]);

            Glide.with(mContext).load(mNormalGoodsList.get(position).getGoodsPic()).into(mHolder.mItemGoodsImg);
            if (goodsEntity.getIsCheck()) {
                mHolder.mItemGoodsSelect.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.shopcar_goods_checkselected));
            } else {
                mHolder.mItemGoodsSelect.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.shopcar_goods_uncheckselected));
            }

            /**
             * 单选
             */
            mHolder.mItemGoodsSelect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    boolean itemIsCheck = mNormalGoodsList.get(position).getIsCheck();
                    if (itemIsCheck) {
                        mHolder.mItemGoodsSelect.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.shopcar_goods_uncheckselected));
                        itemIsCheck = !itemIsCheck;
                        mNormalGoodsList.get(position).setIsCheck(itemIsCheck);
                        if (mGoodsSelectStatusListener != null) {
                            mGoodsSelectStatusListener.setGoodsSelectStatusResult(null, position, itemIsCheck);
                        }
                    } else {
                            if (mNormalGoodsList.get(position).getGoodsNum() < 1) {
                                mContext.showDialog(null, "所选商品数量不能小于0");
                                return;
                            }else if (mNormalGoodsList.get(position).getGoodsAllNum() < mNormalGoodsList.get(position).getGoodsNum()) {
                                mContext.showDialog(null, "库存量不足");
                                return;
                            }else if (mNormalGoodsList.get(position).getGoodsStatus() != 1) {
                                mContext.showDialog(null, "商品已失效");
                                return;
                            }else {
                                mHolder.mItemGoodsSelect.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.shopcar_goods_checkselected));
                                itemIsCheck = !itemIsCheck;
                                mNormalGoodsList.get(position).setIsCheck(itemIsCheck);
                                if (mGoodsSelectStatusListener != null) {
                                    mGoodsSelectStatusListener.setGoodsSelectStatusResult(null, position, itemIsCheck);
                                }
                            }
                    }
                }
            });
            /**
             * 商品数量添加
             */

            mHolder.mItemGoodsCountAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                if(!isAccount){
//                    return;
//                }

                    if (isFastDoubleClick()) {
                        return;
                    }
                    if (mNormalGoodsList.get(position).getGoodsNum() + 1 > mNormalGoodsList.get(position).getGoodsAllNum()) {
                        mContext.showDialog(null, "库存量不足");
                        return;
                    } else if (1 != mNormalGoodsList.get(position).getGoodsStatus()) {
                        mContext.showDialog(null, "商品已失效");
                        return;
                    } else{
                        mGoodsCountChangeListener.setCountChange(position, String.valueOf(goodsEntity.getGoodsNum() + 1), true);
                    }
                }
            });
            /**
             * 商品数量减少
             */
            mHolder.mItemGoodsCountSubtract.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                if(!isAccount){
//                    return;
//                }
                    if (isFastDoubleClick()) {
                        return;
                    }
//                if(mGoodsList.get(position).getGoogdsnum() + 1 > mGoodsList.get(position).getAllNum()){
//                    mContext.showErrorDialog(null,"库存量不足");
//                    return;
//                }
                    if (1 != mNormalGoodsList.get(position).getGoodsStatus()) {
                        mContext.showDialog(null, "商品已失效");
                        return;
                    } else if (mNormalGoodsList.get(position).getGoodsNum() - 1 < 1) {
                        return;
                    }else {
                        if(mNormalGoodsList.get(position).getGoodsNum() - 1 > mNormalGoodsList.get(position).getGoodsAllNum()){
                            mNormalGoodsList.get(position).setIsCheck(false);
                        }
                        mGoodsCountChangeListener.setCountChange(position, String.valueOf(goodsEntity.getGoodsNum() - 1), false);
                    }
                }
            });

            mHolder.mItemGoodsImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, ProductInfoActivity.class);
                    intent.putExtra(INTENT_PRODUCTID, String.valueOf(mNormalGoodsList.get(position).getGoodsID()));
                    intent.putExtra("shopCarRes", 110);
                    mContext.startActivity(intent);
                }
            });

            mHolder.mItemGoodsDescribe.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, ProductInfoActivity.class);
                    intent.putExtra(INTENT_PRODUCTID, String.valueOf(mNormalGoodsList.get(position).getGoodsID()));
                    intent.putExtra("shopCarRes", 110);
                    mContext.startActivity(intent);
                }
            });
            mHolder.mItemGoodsName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, ProductInfoActivity.class);
                    intent.putExtra(INTENT_PRODUCTID, String.valueOf(mNormalGoodsList.get(position).getGoodsID()));
                    intent.putExtra("shopCarRes", 110);
                    mContext.startActivity(intent);
                }
            });

        } else if (getItemViewType(position) == FAILURE_GOODS) {
            ShopCarFailureViewHolder mHolder = (ShopCarFailureViewHolder) holder;
            mHolder.initView(mFailureGoodsList.get(position - 1 - mNormalGoodsList.size()));
        } else if (getItemViewType(position) == FAILURE_GOODS_DEVIDE && getItemCount() > mNormalGoodsList.size() + 1) {
            ShopCarFailureDevideViewHolder mHolder = (ShopCarFailureDevideViewHolder) holder;
            mHolder.initData(mDelFailureGoodsListener);
        }
    }


    @Override
    public int getItemViewType(int position) {
//        return super.getItemViewType(position);
        if (position < mNormalGoodsList.size()) {
            return NORMAL_GOODS;
        } else if (position == mNormalGoodsList.size()) {
            return FAILURE_GOODS_DEVIDE;
        } else {
            return FAILURE_GOODS;
        }
    }

    @Override
    public int getItemCount() {
        if(mGoodsList.size() == mNormalGoodsList.size()){
            return mNormalGoodsList.size();
        }
        return mNormalGoodsList.size() + 1 + mFailureGoodsList.size();
    }

    protected class ShopCarViewHolder extends BaseViewHolder {


        private ImageView mItemGoodsSelect;
        private TextView mItemGoodsName, mItemGoodsPrice;  // 商品名称 价格
        private TextView mItemGoodsCountAdd, mItemGoodsCountSubtract;  // 商品数量添加减少
        private TextView mItemGoodsCount;  // 商品数量
        private TextView mItemGoodsPriceRemainder; // 价格后缀
        private TextView mItemGoodsDescribe;  // 商品描述
        private ImageView mItemGoodsImg; // 商品缩略图

        public ShopCarViewHolder(View itemView) {
            super(itemView);
            mItemGoodsCount = (TextView) itemView.findViewById(R.id.shopCar_Goods_count);
            mItemGoodsCountAdd = (TextView) itemView.findViewById(R.id.shopCar_Goods_count_Add);
            mItemGoodsCountSubtract = (TextView) itemView.findViewById(R.id.shopCar_Goods_subtract);
            mItemGoodsName = (TextView) itemView.findViewById(R.id.shopCar_Goods_name);
            mItemGoodsPrice = (TextView) itemView.findViewById(R.id.shopCar_Goods_price);
            mItemGoodsSelect = (ImageView) itemView.findViewById(R.id.shopCar_item_select_status);
            mItemGoodsPriceRemainder = (TextView) itemView.findViewById(R.id.shopCar_Goods_price_remainder);
            mItemGoodsDescribe = (TextView) itemView.findViewById(R.id.shopcar_goods_describe);
            mItemGoodsImg = (ImageView) itemView.findViewById(R.id.shopCar_item_Goods_img);

        }
    }

    private boolean isAccount = true;

    /**
     * 商品数量是否可更改
     *
     * @param selectType
     */
    public void setSelectType(boolean selectType) {
        isAccount = selectType;
    }

    public void setGoodsSelectListener(GoodsSelectStatusListener goodsSelectListener) {
        this.mGoodsSelectStatusListener = goodsSelectListener;
    }

    private GoodsCountChangeListener mGoodsCountChangeListener;

    public void setGoodsCountChangeListener(GoodsCountChangeListener goodsCountChangeListener) {
        mGoodsCountChangeListener = goodsCountChangeListener;
    }

    private ShopCarDelFailureGoodsListener mDelFailureGoodsListener;

    public void setDelFailureGoodsListener(ShopCarDelFailureGoodsListener delFailureGoodsListener) {
        mDelFailureGoodsListener = delFailureGoodsListener;
    }

    /**
     * 防止双点
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 700) {
            return true;
        }
        lastClickTime = time;
        return false;
    }
}
